﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace BlankApp1.ViewModels
{
    public class ItemModel : BindableBase
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class UserControl1ViewModel : BindableBase, INavigationAware
    {
        // 定义命令属性
        public DelegateCommand SaveCommand { get; }
        public DelegateCommand<int?> DeleteCommand { get; } // 带参数的命令

        public ObservableCollection<ItemModel> Items { get; set; }

        private ItemModel _selectedItem;
        public ItemModel SelectedItem
        {
            get => _selectedItem;
            set
            {
                SetProperty(ref _selectedItem, value);
                DeleteCommand.RaiseCanExecuteChanged(); // 显式通知命令更新
            }
        }
        private bool CanDelete => SelectedItem != null;

        public UserControl1ViewModel()
        {
            // 初始化命令，传入执行方法
            SaveCommand = new DelegateCommand(OnSave);

            // 带条件判断的命令（CanExecute方法）
            DeleteCommand = new DelegateCommand<int?>(OnDelete)
                .ObservesCanExecute(() => CanDelete);


            // 初始化并添加数据
            Items = new ObservableCollection<ItemModel>
            {
                new ItemModel { Id = 1, Name = "项目1" },
                new ItemModel { Id = 2, Name = "项目2" },
                new ItemModel { Id = 3, Name = "项目3" },
                new ItemModel { Id = 4, Name = "项目4" },
            };
        }

        private void OnSave()
        {
            // 保存逻辑
            MessageBox.Show("已保存");
        }

        private void OnDelete(int? id)
        {
            if(CanDelete)
            {
                if (id == null)
                {
                    // 处理空ID的情况
                    return;
                }
                else
                {
                    // 删除指定ID的项
                    MessageBox.Show($"已删除ID为{id}的项");
                    // 现在可以安全地处理整数 ID
                    var item = Items.FirstOrDefault(i => i.Id == id);
                    if (item != null)
                        Items.Remove(item);
                }
            }
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            MessageBox.Show("已导航到UserControl1");
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            MessageBox.Show("OnNavigatedFrom UserControl1");
        }
    }
}
